package com.cardone.platform.common.dao;

import com.cardone.context.Attributes;
import com.cardone.context.ContextHolder;
import com.cardone.persistent.builder.Model;
import com.cardone.persistent.builder.ModelArgs;
import com.cardone.persistent.builder.ModelUtils;
import com.cardone.persistent.support.JdbcTemplateSupport;
import com.cardone.platform.common.dto.EntityLogDto;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 实体日志
 *
 * @author yaohaitao
 */
@Getter
@Setter
@lombok.extern.slf4j.Slf4j
public class EntityLogJdbcDao extends com.cardone.persistent.support.SimpleJdbcDao<com.cardone.platform.common.dto.EntityLogDto> implements EntityLogDao {
    public EntityLogJdbcDao() {
        super(EntityLogDao.SqlIds.ROOT);
    }

    @Override
    protected boolean isBlankById(EntityLogDto dto) {
        return StringUtils.isBlank(dto.getId());
    }

    @Override
    protected void setId(EntityLogDto dto) {
        dto.setId(UUID.randomUUID().toString());
    }

    @Override
    public int updateByEntityIdAndTypeIdForInvalid(final EntityLogDto updateEntityLog) {
        final Model model = ModelUtils.newModel(new ModelArgs(updateEntityLog).setIsSimple(true));

        return ContextHolder.getBean(JdbcTemplateSupport.class).update(SqlIds.updateByEntityIdAndTypeIdForInvalid.id(), model);
    }

    @Override
    public List<Map<String, Object>> findListByEntityIdAndTopN(String entityId, Integer topN) {
        Map<String, Object> model = Maps.newHashMap();

        model.put("entityId", entityId);
        model.put("topN", topN);

        return this.findListBy(SqlIds.findByEntityIdAndTopN.id(), model);
    }

    @Override
    public int updateByClient(String clientId, String id, String dataStateId) {
        Map<String, Object> model = Maps.newHashMap();

        model.put("clientId", clientId);
        model.put("id", id);
        model.put("dataStateId", dataStateId);

        return ContextHolder.getBean(JdbcTemplateSupport.class).update(SqlIds.updateByClient.id(), model);
    }

    @Override
    public String readEntityIdByIdForValid(final String id) {
        final Map<String, Object> model = Maps.newHashMap();

        model.put(Attributes.id.name(), id);

        return ContextHolder.getBean(JdbcTemplateSupport.class).read(String.class, SqlIds.readEntityIdByIdForValid.id(), model);
    }
}
